package session_login.servlet;

import session_login.entity.User;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(name = "IndexServlet", urlPatterns="/IndexServlet")
public class IndexServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 解决乱码问题
    response.setContentType("text/html;charset=utf-8");
    // 创建或者获取保存用户信息的Session对象
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");
    PrintWriter w = response.getWriter();
    if (user == null) {
        w.print("您还没有登录，请<a href='login.html'>登录</a>");
    } else {
        w.print("您已登录，欢迎你，" + user.getUsername() + "!");
        w.print("<a href='LogoutServlet'>退出</a>");
        // 创建Cookie存放Session
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60 * 30);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}